package com.ruoyi.business.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.wecom.client.WeComUtils;
import com.ruoyi.common.wecom.constants.WeComUrlConstants;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.common.engine.api.delegate.event.FlowableEventType;
import org.flowable.common.engine.impl.event.FlowableEntityEventImpl;
import org.flowable.engine.HistoryService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.identitylink.api.IdentityLink;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import static com.ruoyi.flowable.common.constant.TaskConstants.PROCESS_INITIATOR;

/**
 * Flowable 全局监听器
 * 注册到任务创建时
 *
 * @author zyb
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TaskCreateListener implements FlowableEventListener {

    private final TaskService taskService;
    private final WeComUtils weComUtils;
    private final ISysUserService userService;
    @Resource
    protected HistoryService historyService;

    @Override
    public Collection<? extends FlowableEventType> getTypes() {
        return null;
    }

    @Override
    public void onEvent(FlowableEvent flowableEvent) {
        TaskEntity taskEntity = (TaskEntity) ((FlowableEntityEventImpl) flowableEvent).getEntity();
        // 如果是发起人自己的完成 直接跳过
        if (("faqiren".equals(taskEntity.getTaskDefinitionKey()) || "fqr".equals(taskEntity.getTaskDefinitionKey()))) {
            return;
        }
        String taskId = taskEntity.getId();
        List<IdentityLink> idList = taskService.getIdentityLinksForTask(taskId);
        if (CollUtil.isEmpty(idList)) {
            return;
        }
        // 获取接收人
        Long targetUserId = Long.parseLong(idList.get(0).getUserId());
        SysUser sysUser = userService.selectUserById(targetUserId);
        if (ObjUtil.isNull(sysUser)) {
            throw new ServiceException("根据userId未找到对应用户");
        }
        // 流程实例
        HistoricProcessInstance historicProcIns = historyService.createHistoricProcessInstanceQuery()
            .processInstanceId(taskEntity.getProcessInstanceId()).includeProcessVariables().singleResult();
        Map<String, Object> proInstVariables = historicProcIns.getProcessVariables();
        // 发起人
        SysUser fqrUser = userService.selectUserById(Long.parseLong((String) proInstVariables.get(PROCESS_INITIATOR)));
        weComUtils.sendTextMessage(sysUser.getUserName(), WeComUrlConstants.TITLE_1, historicProcIns.getProcessDefinitionName() + ";项目：" + proInstVariables.getOrDefault("projectName", ""), fqrUser.getNickName());
    }

    @Override
    public boolean isFailOnException() {
        return false;
    }

    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }

    @Override
    public String getOnTransaction() {
        return null;
    }
}
